<?php

namespace app\api\service;

use app\common\model\Order;
use app\common\model\OrderItem;
use think\Log;

class PayService extends BaseService
{

    /**
     * 去支付
     * @param $param
     * @param $openId
     * @return \addons\epay\library\Collection|\addons\epay\library\RedirectResponse|\addons\epay\library\Response|false|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ToPay($param, $userId, $openId)
    {


        $order = Order::Where([
            'order_no'   => $param['order_no'],
            'user_id'    => $userId,
            'status'     => Order::STATUS_PENDING,
            'pay_status' => Order::PAY_STATUS_FALSE,
        ])->find();
        if (empty($order)) {
            $this->setMsg('找不到相关记录');
            return false;
        }

        $params = [
            'amount' => $order['total_amount'],
            'orderid' => $order['order_no'],
            'type' => $param['type'],
            'title' => ($order['type'] == Order::TYPE_DRESSUP ? "套餐" : "商品") . $order['order_no'],
            'method' => $param['method'],
            'openid' => $openId ?? "",
        ];
        return \addons\epay\library\Service::submitOrder($params);
    }

    /**
     * 支付回调 【未完成】
     * @param $param
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function notify($param)
    {

        $orderNo = $param['order_no'];
        // 1、查出订单信息
        $order = Order::Where('order_no', $orderNo)->find();
        if (empty($order)) {
            echo "fail";
            return false;
        }
        $orderId = $order['id'];
        $userId = $order['user_id'];
        $orderType = $order['type'];
        $orderAmount = $order['total_amount'];
        $paymentType = $order['payment_type'];


        // 2、查出订单项目信息
        $orderItem = OrderItem::Where('order_id', $orderId)->find();
        $dataType = $orderItem['data_type'];
        $dataId = $orderItem['data_id'];
        $packagedId = 0;
        $productId = 0;
        if ($dataType == OrderItem::DATA_TYPE_PACKAGED) {
            $packagedId = $dataId;
        } else {
            $productId = $dataId;
        }

        $dressupIds = [];
        if ($orderItem['data_type'] == OrderItem::DATA_TYPE_PACKAGED) {
            $dressupIds = json_decode($orderItem['content'], true)['dressup_ids'];
        }

        // 3、设置订单回调信息
        $payAmount = $param['payed_amount']; // 12
        $payedTime = $param['payed_time']; // 1726709931
        $payType = $param['pay_type']; // wechat
        $orderService = new OrderService();
        $res = $orderService->callBack($orderId, $param['out_order_no'], $payAmount, $payedTime, $payType);

        if (!$res) {
            echo "fail";
            Log::write('订单回调修改状态失败 :' . $res, 'error');
            return false;
        }

        if ($orderItem['data_type'] == OrderItem::DATA_TYPE_PACKAGED) {
            // 4、设置用户装扮信息
            $service = new UserDressupPackagedService();
            $res = $service->callBack($userId, $packagedId, $dressupIds);
            if (!$res) {
                echo "fail";
                Log::write('设置用户装扮失败 :' . $res, 'error');
                return false;
            }
        }

        echo "success";
        return true;
    }
}
